<template>
    <div class="control list_container flex both-100">
        <div class="content_container">
            <!-- 新增 -->
            <el-form ref="searchForm" :model="searchMap">
                <div class="search_wrapper flex-space-between el-form--inline" style="margin-top: 20px;">
                    <div class="edit">
                        <el-form-item class="flex">
                            <el-button @click="handleAdd()" class="btn_primary el-icon-plus">新增</el-button>
                        </el-form-item>
                    </div>

                </div>
            </el-form>
            <div class="table_container">
                <!-- 表格 -->
                <el-table :data="dataList" v-loading="loading" stripe class="per_table" style="width: 100%" height="500">
                    <el-table-column type="index" width="300" label="序号" align="center" />
                    <el-table-column prop="emergencyPlanName" label="预案名称" align="center"></el-table-column>
                    <el-table-column prop="recordNum" label="备案号" width="200" align="center"></el-table-column>
                    <el-table-column label="操作" width="280">
                        <template slot-scope="scope">
                            <div>
                                <span type="text" class="tag_primary" size="small"
                                    @click="handleSelect(scope.row)">查看</span>
                                <span type="text" class="marginl-10 tag_primary" size="small"
                                    @click="handleEdit(scope.row)">编辑</span>
                                <span type="text" class="marginl-10 tag_warning" size="small"
                                    @click="handleDelete(scope.row)">删除</span>
                                <span>
                                    <el-dropdown @command="handleCommand" v-if="scope.row.attachment.length > 0">
                                        <span class="el-dropdown-link">
                                            <span type="text" class="marginl-10 tag_warning" size="small">下载附件</span>
                                        </span>
                                        <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item v-for="(item, index) in scope.row.attachment" :key="index"
                                                :command="item">{{ handleStr(item) }}</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                    <span class="el-dropdown-link" v-else>
                                        <span type="text" class="marginl-10 tag_warning" size="small">暂无附件</span>
                                    </span>
                                </span>


                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 分页 -->
            <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum" :limit.sync="searchMap.pageSize"
                @change="getList"></Pagination>
        </div>

        <!-- 弹窗 详情 -->
        <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisible" width="800" append-to-body
            :before-close="() => { dialogVisible = false }" :close-on-click-modal="false">
            <div class="content">
                <el-form ref="form" :model="formModel" :rules="formRules" size="small" label-width="80px"
                    >
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="备案号" label-width="120px" prop="recordNum">
                                <el-input v-model="formModel.recordNum" placeholder="请输入备案号"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预案名称" label-width="120px" prop="emergencyPlanName">
                                <el-input v-model="formModel.emergencyPlanName" placeholder="请输入预案名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="备案时间" label-width="120px" prop="recordTime">
                                <el-date-picker v-model="formModel.recordTime" type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预案类型" label-width="120px" prop="emergencyPlanType">
                                <el-select v-model="formModel.emergencyPlanType" placeholder="请选择预案类型" style="width: 100%;">
                                    <el-option v-for="(item, index) in dict.type.reserve_plan_type" :label="item.label"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="属性" label-width="120px" prop="enableStatus">
                                <template>
                                    <el-radio v-model="formModel.enableStatus" label="1">有效</el-radio>
                                    <el-radio v-model="formModel.enableStatus" label="0">无效</el-radio>
                                </template>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="附件" label-width="120px">
                                <uploadFile :value="formModel.attachment"
                                    :fileType="fileType" @change="changeImg" @remove="removeImg"></uploadFile>
                                <p style="color:red;">支持扩展名：.pdf .bmp .gif .jpg .jpeg .png</p>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            
            <div slot="footer" class="dialog-footer" >
                <el-button @click="() => { dialogVisible = false }" class="btn_cancel">取 消</el-button>
                <el-button type="primary" @click="submitFrom()" class="btn_primary">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="title" :visible.sync="dialogVisibleInfo" width="800" append-to-body>
            <custom-title title="详细信息" />
            <BaseDescriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="formModel">
                <template #emergencyPlanType>
                    <dict-tag :options="dict.type.reserve_plan_type" :value="formModel.emergencyPlanType" />
                </template>
                <template #enableStatus>
                    {{ formModel.enableStatus === '1' ? '有效' : '无效' }}
                </template>
                <template #attachment>
                    <uploadFile :isUploadShow="false" :value="formModel.attachment" :deleteFlag="true" :fileType="fileType"
                        @change="changeImg" @remove="removeImg">
                    </uploadFile>
                </template>
            </BaseDescriptions>
        </el-dialog>
    </div>
</template>
<script>
import { emergencyPlanHandle, emergencyPlanList, emergencyPlanExport } from '../api/index'
import BaseDescriptions from '@/components/PageContent/BaseDescriptions.vue';
import uploadFile from '@/components/UploadFiles2/index'

import axios from 'axios';

export default {
    name: 'emergency',
    dicts: ['reserve_plan_type'],
    components: {
        uploadFile,
        BaseDescriptions
    },
    props: {
        projectPointInfo: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            loading: true,
            dialogVisibleInfo: false,
            total: 0,
            title: '应急预案详情',
            formType: 'basicInformation',
            dialogVisible: false,
            searchMap: {
                pageNum: 1,
                pageSize: 10,
            },
            dataList: [],
            fileType: ['pdf', 'bmp', 'gif', 'jpg', 'jpeg', 'png'],
            // 提交表单数据
            formModel: {
                attachment: [],
            },
            reqType: 'post',
            formRules: {
                recordNum: {
                    required: true,
                    message: "备案号不能为空",
                    trigger: "change",
                },
                emergencyPlanName: {
                    required: true,
                    message: "预案名称不能为空",
                    trigger: "change",
                },
                recordTime: {
                    required: true,
                    message: "请选择时间",
                    trigger: "change",
                },
                emergencyPlanType: {
                    required: true,
                    message: "请选择类型",
                    trigger: "change",
                },
                enableStatus: {
                    required: true,
                    message: "请选择",
                    trigger: "change",
                },
            },
            descConfig: {
                size: 'medium',
                column: '2',
            },
            descConfigItem: [
                {
                    fieIdName: 'recordNum',
                    label: '备案号',
                    span: 2,
                },
                {
                    fieIdName: 'emergencyPlanName',
                    label: '预案名称',
                    span: 2,
                },
                {
                    fieIdName: 'recordTime',
                    label: '备案时间',
                    span: 2,
                },
                {
                    fieIdName: 'emergencyPlanType',
                    label: '预案类型',
                    span: 2,
                    slotName: 'emergencyPlanType',
                },
                {
                    fieIdName: 'enableStatus',
                    label: '属性',
                    span: 12,
                    slotName: 'enableStatus',
                },
                {
                    fieIdName: 'attachment',
                    label: '附件',
                    span: 12,
                    slotName: 'attachment',
                },
            ],
        }
    },
    methods: {
        submitFrom() {
            this.formModel.projectPointId = this.projectPointInfo.projectPointId
            console.log(this.formModel)
            this.$refs.form.validate((valid) => {
                if (valid) {
                    emergencyPlanHandle(this.formModel, this.reqType).then(res => {
                        if (200 === res.code) {
                            this.$message({
                                message: '操作成功',
                                type: 'success',
                            });
                            this.dialogVisible = false
                            this.formModel = {}
                            this.getList()
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        //删除
        handleDelete(row) {
            this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                emergencyPlanHandle([row.emergencyPlanId], 'delete').then(res => {
                    if (200 === res.code) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList()
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        //新增打开
        handleAdd() {
            this.title = "新增应急预案"
            this.reqType = 'post'
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
            this.formModel = {}
            this.$set(this.formModel, 'attachment', [])
            this.dialogVisible = true;
        },
        //编辑
        handleEdit(row) {
            this.title = "编辑应急预案"
            this.formModel = row
            this.$set(this.formModel, 'attachment', row.attachment)
            this.reqType = 'put'
            this.dialogVisible = true;
        },
        //查看
        handleSelect(row) {
            this.title = "应急预案详情"
            this.reqType = 'select'
            this.formModel = row
            this.dialogVisibleInfo = true;
        },
        //下载
        handleDownload(row) {
            console.log(row)
            // this.downloadByBlob(this.$store.state.config.inFilePrefix + row.picUrl, 'pic')
        },
        handleCommand(command) {
            console.log(command)
            const extension = command.match(/\.(\w+)$/)[1];
            if (extension === 'pdf') {
                this.downloadPdfBlob(this.$store.state.config.inFilePrefix + command, '附件')
            } else {
                this.downloadByBlob(this.$store.state.config.inFilePrefix + command, '附件')
            }
        },
        downloadPdfBlob(url, name) {
            console.log('22')
            axios({
                url: url,
                method: 'GET',
                responseType: 'blob'
            }).then(res => {
                let blob = new Blob([res.data], { type: 'application/pdf' })
                let url = window.URL.createObjectURL(blob)
                let a = document.createElement('a')
                a.href = url
                a.download = name
                a.click()
                a.remove()
                window.URL.revokeObjectURL(url)
            })
        },
        downloadByBlob(url, name) {
            console.log('11')
            let image = new Image();
            image.setAttribute("crossOrigin", "anonymous");
            image.src = url;
            image.onload = () => {
                let canvas = document.createElement("canvas");
                canvas.width = image.width;
                canvas.height = image.height;
                let ctx = canvas.getContext("2d");
                ctx.drawImage(image, 0, 0, image.width, image.height);
                canvas.toBlob(blob => {
                    let url = URL.createObjectURL(blob);
                    let a = document.createElement("a");
                    a.download = name;
                    a.href = url;
                    a.click();
                    a.remove();
                    // 用完释放URL对象
                    URL.revokeObjectURL(url);
                });
            };
        },
        handleStr(val) {
            console.log(val)
            const parts = val.split('/');
            return parts[parts.length - 1]
        },
        // 项目点图片修改
        changeImg(item) {
            if (!this.formModel.attachment) {
                this.formModel.attachment = []
            }
            this.formModel.attachment.push(item.url)
        },
        removeImg(item) {
            this.formModel.attachment.splice(this.formModel.attachment.indexOf(item.url), 1)
        },
        // 页面数据
        async getList() {
            const { code, rows, total } = await emergencyPlanList(this.searchMap)
            if (code === 200) {
                this.loading = false
                this.dataList = rows
                this.total = total
            }
        },
    },
    mounted() {
        this.searchMap.projectPointId = this.projectPointInfo.projectPointId
        this.getList()
    },
}
</script>
<style lang="less">
.control {
    .el-table__cell {
        .cell {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}
</style>
<style lang="less" scoped>
.list_container {
    flex-direction: column;
    background: url("@/assets/images/home/content.png") no-repeat;
    background-size: cover;

    .content_container {
        padding: 15px 20px;
        overflow-y: scroll;
    }

    .table_container {
        margin-bottom: 25px;
    }

    .pagination_container {
        display: flex;
        justify-content: space-between;
        height: 32px;
    }
}
</style>